package com.mdd.common.entity.yangyangLeadingEnterprise.common;


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieSession<T>  {
	
	
	public  void save(HttpServletResponse rep,String name,T obj)
	{

		Serializer<T> s=new Serializer<T>();
		
		
		Cookie c=new Cookie(name,s.toString(obj));
		
		rep.addCookie(c);
	}
	
	public  void save(HttpServletResponse rep,String name,T obj,String cookie_path)
	{

		Serializer<T> s=new Serializer<T>();
		
		
		Cookie c=new Cookie(name,s.toString(obj));
		c.setPath(cookie_path);
		c.setMaxAge(Integer.MAX_VALUE);
		rep.addCookie(c);
	}
	public T read(HttpServletRequest req,String name,Class<T> clazz)
	{
		Cookie cs[]=req.getCookies();
		if(cs==null) return null;
		
		for(Cookie c:cs)
		{
			if(c.getName().equals(name))
			{
				
				Serializer<T> s=new Serializer<T>();	
				return s.toObject(c.getValue(), clazz);
			}	
		}	
	    return null;
	}
	public  void remove(HttpServletRequest req,HttpServletResponse rep,String name)
	{
		Cookie c=new Cookie(name,null);
		c.setMaxAge(0);
        c.setPath("/"); 
		rep.addCookie(c);
	}
}
